package org.example.admin.filter;

import org.example.entity.UserSystem;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 过滤所有请求
 */
@WebFilter("/admin/*")
public class SessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req= (HttpServletRequest) servletRequest;
        //打印客户端访问的地址
        //创建集合:放行的集合(白名单)
        List<String> list = new ArrayList<>();
        list.add("/admin/commons/");
        list.add("/admin/css/");
        list.add("/admin/fonts/");
        list.add("/admin/img/");
        list.add("/admin/images/");
        list.add("/admin/js/");
        list.add("/admin/login.jsp");

        //循环集合
        for(String path :list){
            //获取当前访问的路径，类型转换成String
            String reqPath = req.getRequestURL().toString();
            //判断是否包含白名单
            if(reqPath.contains(path)){
                //如果有的话就放行
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        //如果请求不在白名单，需要判断session域
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        HttpSession session = req.getSession();
        UserSystem userSession = (UserSystem) session.getAttribute("userSession");
        if (userSession!=null&&userSession.getId()>0){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }


        resp.sendRedirect("/admin/login.jsp");

    }

    @Override
    public void destroy() {

    }
}
